package org.scc.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.scc.model.User;

public class LoginFilter implements Filter {
	
	private String filterPattern;
	
	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		HttpServletResponse httpResponse = (HttpServletResponse)response;
		
		String requestURI = httpRequest.getRequestURI();
		
		String page = requestURI.substring(httpRequest.getContextPath().length());
		
		HttpSession session = httpRequest.getSession();
		User user = (User) session.getAttribute("user");
		if(page.matches(filterPattern)){
			if(user == null && !page.equals("/login.jsp") && !page.equals("/user/login.do")){
				httpResponse.sendRedirect(httpRequest.getContextPath() + "/login.jsp");
				return ;
			}
		}
		chain.doFilter(request, response);
	}
	
	public void init(FilterConfig config) throws ServletException {
		filterPattern = config.getInitParameter("filterPattern");
		System.out.println(filterPattern);
	}

}
